package com.txby.platformApi.component.web;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.jck.mybatis.log.GlobalLogAnnotation;
import com.jck.mybatis.util.PageBean;
import com.jck.mybatis.util.PageList;
import com.jck.tools.ChkUtil;
import com.jck.tools.DateAirth;
import com.txby.platformApi.component.service.SpringContextUtils;
import com.txby.platformCore.component.service.CommonController;
import com.txby.platformCore.component.util.GTPushUtil;
import com.txby.platformCore.component.util.XGPushUtil;
import com.txby.platformCore.data.CommonApiModelMapExt;
import com.txby.platformCore.data.CommonXGRetunInfo;
import com.txby.platformCore.entity.DeviceGTServerSign;
import com.txby.platformCore.entity.DeviceRemindJobMsg;
import com.txby.platformCore.entity.DeviceXGServerSign;
import com.txby.platformCore.entity.DeviceXGtoken;
import com.txby.platformCore.entity.HosCallInfoConfirm;
import com.txby.platformCore.entity.HosCallInfoConfirmRespond;
import com.txby.platformCore.entity.ProductDeviceInit;
import com.txby.platformCore.entity.SickDetailInfo;
import com.txby.platformCore.entity.SysAnswer;
import com.txby.platformCore.entity.Sysversion;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONArray;

/**
 * api信息
* @author 作者 jacking
* @date  
 */
@SuppressWarnings("all")
@RestController
@Api(value="api信息",description="api信息-说明")
@RequestMapping("/app")
public class AppController extends CommonController{
	private static Logger log = Logger.getLogger(AppController.class);
/*	private static DeviceGTServerSign dxs=SpringContextUtils.getDeviceGTServerSign();
	private static DeviceXGServerSign dxgs=SpringContextUtils.getDeviceXGServerSign();*/
	
/*	@ApiOperation(value = "保存患者基本信息", notes = "保存患者基本信息-说明")
	@PostMapping("/saveSickBaseInfo/{type}/{token}")
	@ApiImplicitParams({
		@ApiImplicitParam(paramType="query",dataType="number",name="type",value="请求端（ 0:web,1:android,2:iphone）",required=true),
		@ApiImplicitParam(paramType="query",dataType="string",name="token",value="用户令牌",required=true)
	})*/
	/**
	 * 
	 * @param type
	 * @param token
	 * @param deviceXGtoken
	 * @param deviceUseType 0:患者1：护士2：医生3:推送护士站
	 * @return
	 */
	@ApiOperation(value = "保存设备信鸽信息", notes = "保存设备信鸽信息-说明")
	@PostMapping("/saveDeviceXGtoken/{type}/{token}")
	@GlobalLogAnnotation(logType=2,discription="保存产品设备信鸽绑定token信息")
	public Map saveDeviceXGtoken(@PathVariable("type") Integer type, @PathVariable("token") String token,DeviceXGtoken deviceXGtoken,Integer deviceUseType  ) {
		CommonApiModelMapExt mm = chekTokenCahceValid(token, type);
		if(ChkUtil.isEmpty(deviceUseType))deviceUseType=0;
		try {
			if (!isTokenValid) {
				return mm;
			}
		
			if (deviceXGtoken != null&&!ChkUtil.isEmpty(deviceXGtoken.getDeviceSN())) {
				ProductDeviceInit pdi=this.getProductDeviceInit(deviceXGtoken.getDeviceSN());
				String sql="";
				if(pdi!=null){
					DeviceXGtoken deviceXGtokenOld=(DeviceXGtoken) this.mBaseDao.findBySqlUniqueObject("select * from "+this.mBaseDao.tableName(DeviceXGtoken.class)+" where deviceSN=#{pojo.deviceSN}", DeviceXGtoken.class, new HashMap(){{
						put("deviceSN", deviceXGtoken.getDeviceSN());
					}});
					if(deviceXGtokenOld!=null){
						String id =deviceXGtokenOld.getId();
						BeanUtils.copyProperties(deviceXGtokenOld, deviceXGtoken);
						deviceXGtokenOld.setId(id);
						deviceXGtokenOld.setDeptId(pdi.getDeptId());
						deviceXGtokenOld.setUpdateTime(new Date());
						this.mBaseDao.updateObject(deviceXGtokenOld);
							pdi.setUpdateTime(new  Date());
							if(deviceUseType==3){
								pdi.setBedNO("nurse");
								pdi.setDeviceUseType(deviceUseType);
							}
							this.mBaseDao.updateObject(pdi);
							mm.put(CommonApiModelMapExt.ERRCODE, 0);
							mm.put(CommonApiModelMapExt.ERRMSG, "更新成功");
							return mm;
						}else{
							if (deviceUseType == 3) {
								pdi.setBedNO("nurse");
								pdi.setDeviceUseType(deviceUseType);
							}
							pdi.setUpdateTime(new Date());
							deviceXGtoken.setDeptId(pdi.getDeptId());
							this.mBaseDao.saveObject(deviceXGtoken);
							this.mBaseDao.updateObject(pdi);
							mm.put(CommonApiModelMapExt.ERRCODE, 0);
							mm.put(CommonApiModelMapExt.ERRMSG, "保存成功");
							return mm;
						}
					}else{
						mm.put(CommonApiModelMapExt.ERRCODE, 1);
						mm.put(CommonApiModelMapExt.ERRMSG, "此设备没有产品初始化");
						return mm;
					}
					
				}else{
					mm.put(CommonApiModelMapExt.ERRCODE, 1);
					mm.put(CommonApiModelMapExt.ERRMSG, "参数不正确");
					return mm;
				}
				
		} catch (Exception e) {
			e.printStackTrace();
			mm.put(CommonApiModelMapExt.ERRCODE, 1);
			mm.put(CommonApiModelMapExt.ERRMSG, "系统异常");
		}
		return mm;
	}
	
	@ApiOperation(value = "患者的即时呼叫发送", notes = "患者的即时呼叫发送-说明")
	@PostMapping("/sendOnceCallInfo/{type}/{token}")
	@GlobalLogAnnotation(logType=2,discription="患者的即时呼叫发送")
	/**
	 * 患者的即时呼叫
	 * @param type
	 * @param token
	 * @param callType 呼叫类型（0：紧急呼叫，1：换水呼叫，2：普通呼叫）	 
	 * @param callMsg 消息内容
	 * @param deviceSN 设备编号
	 * @return
	 */
	public Map sendOnceCallInfo(@PathVariable("type") Integer type, @PathVariable("token") String token,@RequestParam(required=true)Integer callType,String callMsg,@RequestParam(required=true)String deviceSN) {
		Map<Integer,String> callMap=new HashMap(){{
			put(0, "紧急呼叫");
			put(1, "换水呼叫");
			put(2, "普通呼叫");
		}};
		CommonApiModelMapExt mm = chekTokenCahceValid(token, type);
		if(callMap.get(callType)==null){
			mm.put(CommonApiModelMapExt.ERRCODE, 1);
			mm.put(CommonApiModelMapExt.ERRMSG, "参数不正确");
			return mm;
		}
		try {
			if (!isTokenValid) {
				return mm;
			}
			if(ChkUtil.isEmpty(callMsg)) callMsg=callMap.get(callType);
			String sql="SELECT t.bedNO,t.deptId,t.deviceSN,t.sickAreaNO,t.sickAreaName,t2.token FROM "+this.mBaseDao.tableName(ProductDeviceInit.class)+"  t INNER JOIN t_txby_deviceXGtoken t2 on t.deviceSN=t2.deviceSN and t.deviceSN=#{pojo.deviceSN}";
			Map param=new HashMap();
			ProductDeviceInit curDeviceInfo= (ProductDeviceInit) this.mBaseDao.findBySqlUniqueObject(sql, ProductDeviceInit.class, new HashMap(){{
				put("deviceSN", deviceSN);
			}});
			int xgType=2;
			Long msgId=0L;
			if (curDeviceInfo != null) {
					sql="SELECT t.bedNO,t.deviceSN,t2.token,t.deviceUseType,t.deptId    FROM  "+this.mBaseDao.tableName(ProductDeviceInit.class)+" t INNER JOIN t_txby_deviceXGtoken t2 on t.deviceSN=t2.deviceSN and t.deptId='"+curDeviceInfo.getDeptId()+"'  and t.sickAreaNO='"+curDeviceInfo.getSickAreaNO()+"' and t.deviceUseType=3 order by t.updateTime desc LIMIT 1";//查询预先设定的护士端pad
				    List<ProductDeviceInit> pushPoint=this.mBaseDao.findBySql(sql, ProductDeviceInit.class, null);
				    if(!ChkUtil.isEmpty(curDeviceInfo.getToken())&&pushPoint.size()>0){
				    	//患者信息后期加入组织
			    	SickDetailInfo sbi =this.getSickDetailInfo(deviceSN);
			    	CommonXGRetunInfo result=null;
			    	Map msgIdMap=new HashMap();
//			    	XGPushUtil xgu=	XGPushUtil.getNewInstance(SpringContextUtils.getDeviceGTServerSign().getAccessId(), dxgs.getSecretKey());
			    	GTPushUtil xu=	GTPushUtil.getNewInstance(SpringContextUtils.getDeviceGTServerSign().getAppID(), SpringContextUtils.getDeviceGTServerSign().getAppKey(), SpringContextUtils.getDeviceGTServerSign().getMasterSecret());
//				    	SickDetailInfo sbi=(SickDetailInfo) this.mBaseDao.findBySqlUniqueObject("select * from "+this.mBaseDao.tableName(SickDetailInfo.class)+" where bedNO='"+curDeviceInfo.getBedNO()+"' and sickAreaNO='"+curDeviceInfo.getSickAreaNO()+"' and deptId='"+curDeviceInfo.getDeptId()+"' and outHosTime is null ", SickDetailInfo.class, null);
				    	for(ProductDeviceInit p:pushPoint){
				    		if(!ChkUtil.isEmpty(p.getToken())){
				    			HosCallInfoConfirm hc=new HosCallInfoConfirm();
				    				hc.setDeptId(curDeviceInfo.getDeptId());
				    				hc.setFromToken(curDeviceInfo.getToken());
				    				hc.setFromDeviceSN(curDeviceInfo.getDeviceSN());
				    				hc.setToToken(p.getToken());
				    				hc.setToDeviceSN(p.getDeviceSN());
				    				hc.setCallType(callType);
				    				hc.setCallMsg(callMsg);
				    				hc.setBedNO(curDeviceInfo.getBedNO());
				    				hc.setSickAreaNO(curDeviceInfo.getSickAreaNO());
				    				this.mBaseDao.saveObject(hc);
				    				msgId=hc.getId_();
				    		
				    			//推送消息
				    			Map custom=new HashMap();
				    			Map data=new HashMap();
				    			data.put("callType", callType);
				    			data.put("discription", callMap.get(callType));
				    			data.put("msgId", msgId);
				    			data.put("bedNO", curDeviceInfo.getBedNO());
				    			data.put("sickAreaName", curDeviceInfo.getSickAreaName());
				    			data.put("callTime", hc.getCreateTime());
				    			if(sbi!=null){
				    				data.put("sickName", sbi.getSickName());
				    			}else {
				    				data.put("sickName", "");
				    			}
				    			custom.put("data", data);
				    		
				    			custom.put("callType", callType);
				    			//查询患者信息
				    	/*		m.put("data", data);
				    			
				    			 m=new HashMap();
				    			 custom=new HashMap();
				    			 data=new HashMap();
				    			m.put("respondType",callType);
				    			m.put("discription", callMap.get(callType));
				    			m.put("msgId", msgId);*/
				    		/*	custom.put("data", m);*/
				    			
//						 result = xgu.pushSingleDeviceCustomMessage(p.getToken(), callMap.get(callType), callMsg,
//									custom, xgType); 
							result = xu.pushSingleDeviceCustomMessage(p.getToken(), custom);
							// xu.pushSingleDeviceCustomMessage(p.getToken(),
							// callMap.get(callType), callMsg, custom,xgType);
						}

					}
				    	if(!ChkUtil.isEmpty(result)){
				    		mm.put("msgId", msgId);
				    		mm.put(CommonApiModelMapExt.ERRCODE, 0);
				    		mm.put(CommonApiModelMapExt.ERRMSG, "成功呼叫到护士站，请等待响应");
				    		System.out.println(mm);
				    		return mm;
				    	}else{
				    		mm.put("msgId", msgId);
				    		mm.put(CommonApiModelMapExt.ERRCODE, 1);
				    		mm.put(CommonApiModelMapExt.ERRMSG, "失败呼叫，请重试");
				    		System.out.println(mm);
				    		return mm;

				    	}
				    	
				    }else{
				    	mm.put(CommonApiModelMapExt.ERRCODE, 1);
						mm.put(CommonApiModelMapExt.ERRMSG, "设备可能没有找到护士端或信鸽未注册");
						System.out.println(mm);
						return mm;
				    }
			} else {
				mm.put(CommonApiModelMapExt.ERRCODE, 1);
				mm.put(CommonApiModelMapExt.ERRMSG, "设备可能没有绑定信鸽未注册");
				System.out.println(mm);
				return mm;
			} 
		} catch (Exception e) {
			e.printStackTrace();
			mm.put(CommonApiModelMapExt.ERRCODE, 1);
			mm.put(CommonApiModelMapExt.ERRMSG, "系统异常");
		}
		System.out.println(mm);
		return mm;
	}
	
	/**
	 * 回复患者的即时呼叫
	 * @param type
	 * @param token
	 * @param deviceXGtoken
	 * @return
	 */
	@PostMapping("/respondOnceCallInfo/{type}/{token}")
	@GlobalLogAnnotation(logType=2,discription="呼叫来源信息")
	/**
	 * 	callType	即时呼叫类别（0：紧急呼叫，1：换水呼叫，2：普通呼叫）	string	是
	callMsg	具体发送的信息	string	
	bedNO	床位号	string	是
	sickAreaNO	病区编号	string	是

	 * @param type
	 * @param token
	 * @param callType
	 * @param callMsg
	 * @param sickAreaNO
	 * @return
	 */
	public Map respondOnceCallInfo(@PathVariable("type") Integer type, @PathVariable("token") String token,@RequestParam(required=true)Integer msgId,@RequestParam(required=true)String deviceSN,String respondMsg) {
		Map<Integer,String> callMap=new HashMap(){{
			put(0, "紧急呼叫");
			put(1, "换水呼叫");
			put(2, "普通呼叫");
		}};
		CommonApiModelMapExt mm = chekTokenCahceValid(token, type);
		try {
			if (!isTokenValid) {
				return mm;
			}
			String sql="SELECT  *  FROM "+this.mBaseDao.tableName( HosCallInfoConfirm.class)+" where id_="+msgId+" and isConfirm=0 ";
			HosCallInfoConfirm curCallInfoConfirm= (HosCallInfoConfirm) this.mBaseDao.findBySqlUniqueObject(sql, HosCallInfoConfirm.class,null);
			if (curCallInfoConfirm != null) {
//				XGPushUtil xgu=	XGPushUtil.getNewInstance(dxgs.getAccessId(), dxgs.getSecretKey());
				GTPushUtil xu=	GTPushUtil.getNewInstance(SpringContextUtils.getDeviceGTServerSign().getAppID(), SpringContextUtils.getDeviceGTServerSign().getAppKey(), SpringContextUtils.getDeviceGTServerSign().getMasterSecret());
				Map m=new HashMap();
    			Map custom=new HashMap();
    			Map data=new HashMap();
    			custom.put("respondType", curCallInfoConfirm.getCallType());
    			custom.put("discription", callMap.get(curCallInfoConfirm.getCallType()));
    			custom.put("msgId", msgId);
//    			if(ChkUtil.isEmpty( respondMsg)) respondMsg=callMap.get(curCallInfoConfirm.getCallType());
//				CommonXGRetunInfo info=xgu.pushSingleDeviceCustomMessage(curCallInfoConfirm.getFromToken(), callMap.get(curCallInfoConfirm.getCallType()), respondMsg,custom, 2);
				CommonXGRetunInfo info=xu.pushSingleDeviceCustomMessage(curCallInfoConfirm.getFromToken(), custom);
				if(info.getRet_code()==0){
					HosCallInfoConfirmRespond  respond=new HosCallInfoConfirmRespond();
					BeanUtils.copyProperties(respond, curCallInfoConfirm);
					respond.setRespondMsg(respondMsg);
					Date date=new Date();
					respond.setCreateTime(date);
					respond.setId(null);
					respond.setUpdateTime(date);
					respond.setHosCallInfoConfirmId(curCallInfoConfirm.getId());
					this.mBaseDao.saveObject(respond);
//					String message="呼叫信息响应成功";
			/*		GlobalLogAspectInterceptor.saveDBLog(this.mBaseDao, new HashMap(){{
						put("message",  message);
						put("type", "respondType");
					}});*/
					curCallInfoConfirm.setIsConfirm(1);
					curCallInfoConfirm.setUpdateTime(new Date());
					this.mBaseDao.updateObject(curCallInfoConfirm);
					mm.put(CommonApiModelMapExt.ERRCODE, 0);
					mm.put(CommonApiModelMapExt.ERRMSG, "呼叫信息响应成功");
					return mm;
				}else{
					mm.put(CommonApiModelMapExt.ERRCODE, 1);
					mm.put(CommonApiModelMapExt.ERRMSG, "信息发送失败，可能服务器繁忙");
					return mm;
				}
			 
				}else{
					mm.put(CommonApiModelMapExt.ERRCODE, 1);
					mm.put(CommonApiModelMapExt.ERRMSG, "无未确认呼叫信息");
					return mm;
				}
		} catch (Exception e) {
			e.printStackTrace();
			mm.put(CommonApiModelMapExt.ERRCODE, 1);
			mm.put(CommonApiModelMapExt.ERRMSG, "系统异常");
		}
		return mm;
	}
	
	
	
	@PostMapping("/sendCancelOnceCallInfo/{type}/{token}")
	@GlobalLogAnnotation(logType=2,discription="呼叫来源信息")
	/**
	 * 	callType	即时呼叫类别（0：紧急呼叫，1：换水呼叫，2：普通呼叫）	string	是
	callMsg	具体发送的信息	string	
	bedNO	床位号	string	是
	sickAreaNO	病区编号	string	是

	 * @param type
	 * @param token
	 * @param callType
	 * @param callMsg
	 * @param sickAreaNO
	 * @return
	 */
	public Map sendCancelOnceCallInfo(@PathVariable("type") Integer type, @PathVariable("token") String token,@RequestParam(required=true)Integer msgId,@RequestParam(required=true)String deviceSN) {
		Map<Integer,String> callMap=new HashMap(){{
			put(0, "紧急呼叫");
			put(1, "换水呼叫");
			put(2, "普通呼叫");
		}};
		CommonApiModelMapExt mm = chekTokenCahceValid(token, type);
		try {
			if (!isTokenValid) {
				return mm;
			}
			String sql="SELECT  *  FROM "+this.mBaseDao.tableName( HosCallInfoConfirm.class)+" where id_="+msgId+"  ";
			HosCallInfoConfirm curCallInfoConfirm= (HosCallInfoConfirm) this.mBaseDao.findBySqlUniqueObject(sql, HosCallInfoConfirm.class,null);
			if (curCallInfoConfirm != null) {
//				XGPushUtil xgu=	XGPushUtil.getNewInstance(dxgs.getAccessId(), dxgs.getSecretKey());
				GTPushUtil xu=	GTPushUtil.getNewInstance(SpringContextUtils.getDeviceGTServerSign().getAppID(), SpringContextUtils.getDeviceGTServerSign().getAppKey(), SpringContextUtils.getDeviceGTServerSign().getMasterSecret());
				Map m=new HashMap();
    			Map custom=new HashMap();
    			Map data=new HashMap();
    			custom.put("callType", curCallInfoConfirm.getCallType());
    			custom.put("cancelType", 1);
    			custom.put("isConfirm", 2);
    			custom.put("discription", callMap.get(curCallInfoConfirm.getCallType()));
    			custom.put("msgId", msgId);
//				CommonXGRetunInfo info=xgu.pushSingleDeviceCustomMessage(curCallInfoConfirm.getToToken(), callMap.get(curCallInfoConfirm.getCallType()), "取消呼叫",custom, 2);
    			CommonXGRetunInfo info=xu.pushSingleDeviceCustomMessage(curCallInfoConfirm.getToToken(), custom);
				if(info.getRet_code()==0){
					curCallInfoConfirm.setIsConfirm(2);
					curCallInfoConfirm.setUpdateTime(new Date());
					this.mBaseDao.updateObject(curCallInfoConfirm);
					mm.put(CommonApiModelMapExt.ERRCODE, 0);
					mm.put(CommonApiModelMapExt.ERRMSG, "呼叫取消成功");
					System.out.println(mm);
					return mm;
				}else{
					mm.put(CommonApiModelMapExt.ERRCODE, 1);
					mm.put(CommonApiModelMapExt.ERRMSG, "信息发送失败，可能服务器繁忙");
					System.out.println(mm);
					return mm;
				}
			 
				}else{
					mm.put(CommonApiModelMapExt.ERRCODE, 1);
					mm.put(CommonApiModelMapExt.ERRMSG, "无此呼叫信息");
					System.out.println(mm);
					return mm;
				}
		} catch (Exception e) {
			e.printStackTrace();
			mm.put(CommonApiModelMapExt.ERRCODE, 1);
			mm.put(CommonApiModelMapExt.ERRMSG, "系统异常");
		}
		System.out.println(mm);
		return mm;
	}
	
/*	@GetMapping("/getDeviceRemindJobMsgList/{type}/{token}")
	@GlobalLogAnnotation(logType=2,discription="查询提醒消息信息")
	public Map getDeviceRemindJobMsgList(@PathVariable("type") Integer type, @PathVariable("token") String token,Integer curPage, Integer pageSize){
		CommonApiModelMapExt mm = chekTokenCahceValid(token, type);
		try {
			if (!isTokenValid) {
				return mm;
			}
			 
			Map paramMap = new HashMap<>();
			curPage=curPage==null?1:curPage;
			pageSize=pageSize==null?10:pageSize;
			String sql="";
			PageList pl=new PageList<>();
//			查询job接口是否异常， 如果异常 则只取本地数据库
			this.isHisErr(DeviceRemindJobMsg.class.getName());
			Map dataMap=new HashMap();
			if(propertySourceConfig.getIsExecuteHisHttp()!=null&&propertySourceConfig.getIsExecuteHisHttp().equals("true")&&!isHisErr){
			 
				
			}else{
			 sql="select * from   "+this.mBaseDao.tableName(DeviceRemindJobMsg.class)+" order by createTime desc ";
			 pl=this.mBaseDao.findBySqlForPageList(sql, DeviceRemindJobMsg.class, new PageBean(curPage, pageSize), null);
			}
			*//**
			 * 请求http数据api
			 *//*
			mm.put("curPage", pl.getPageBean().getPage());
			mm.put("pageSize", pl.getPageBean().getPageSize());
			mm.put("totalCount", pl.getPageBean().getTotalCount());
			mm.put("totalPage", pl.getPageBean().getTotalPage());
			mm.put("data", pl.getResultList());
			mm.put(CommonApiModelMapExt.ERRCODE, 0);
			mm.put(CommonApiModelMapExt.ERRMSG, "查询成功");
			return mm;
			
		} catch (Exception e) {
			e.printStackTrace();
			mm.put(CommonApiModelMapExt.ERRCODE, 1);
			mm.put(CommonApiModelMapExt.ERRMSG, "系统异常");
		}
		

		return mm;
	}*/
	
	
	
	@ApiOperation(value = "根据设备sn号获取app首页查询提醒", notes = "根据设备sn号获取app首页查询提醒")
	@GetMapping("/getQueryReminder/{type}/{token}")
	@GlobalLogAnnotation(logType=2,discription="根据设备sn号获取app首页查询提醒")
	public Map getQueryReminder(@PathVariable("type") Integer type, @PathVariable("token") String token,@RequestParam(name="deviceSN",required=true) String deviceSN , Integer pageSize,Integer curPage ) {
		CommonApiModelMapExt mm = chekTokenCahceValid(token, type);
		DeviceRemindJobMsg drjm=null;
		try {
			if (!isTokenValid ||ChkUtil.isEmpty(deviceSN)) {
				return mm;
			}
			
			if(token.startsWith("demo:")){
				deviceSN=demoDeviceSN;
			}
			ProductDeviceInit pdi=getProductDeviceInit(deviceSN);
			pageSize=pageSize==null?10:pageSize;
			curPage=curPage==null?1:curPage;
			Map paramMap = new HashMap<>();
			
			
			String searchSql = "SELECT * FROM "+this.mBaseDao.tableName(DeviceRemindJobMsg.class)+" WHERE 1=1 and deviceSN =#{pojo.deviceSN}";
			paramMap.put("deviceSN",  deviceSN);
			searchSql += " order by updateTime DESC";// 时间倒序排序
			PageList pl=new PageList<>();
			PageBean pb = new PageBean(curPage,pageSize);
			pl = this.mBaseDao.findBySqlForPageList(searchSql, DeviceRemindJobMsg.class, pb, paramMap);
			if(pl.getResultList().size()>0){
				mm.put(CommonApiModelMapExt.ERRCODE, 0);
				mm.put(CommonApiModelMapExt.ERRMSG, "查询成功");
				mm.put("data",pl.getResultList());
			}else{
				mm.put(CommonApiModelMapExt.ERRCODE, 4500);
				mm.put(CommonApiModelMapExt.ERRMSG, "无数据");
			}
			
			
			return mm;
		} catch (Exception e) {
			e.printStackTrace();
			mm.put(CommonApiModelMapExt.ERRCODE, 1);
			mm.put(CommonApiModelMapExt.ERRMSG, "系统异常");
			mm.put("data",drjm);
		}
		return mm;
	}
	/**
	 * flag 0=demo;1=release
	 * 
	 * pType 0为sick 1为nurse  
	 * pType  
	* @Title: getVersion 
	* @Description: TODO(这里用一句话描述这个方法的作用) 
	* @param @param type
	* @param @param token
	* @param @param flag
	* @param @param appName
	* @param @param pType
	* @param @return    设定文件 
	* @return Map    返回类型 
	* @throws
	 */
	@ApiOperation(value = "查询版本更新", notes = "查询版本更新")
	@GetMapping("/getVersion/{type}/{token}")
	@GlobalLogAnnotation(logType=2,discription="查询版本更新")
	public Map getVersion(@PathVariable("type") Integer type, @PathVariable("token") String token ,Integer flag,Integer pType) {//sick(0),nurse (1)
		CommonApiModelMapExt mm = chekTokenCahceValid(token, type);
		Sysversion sysversion=null;
		try {
			/*if (!isTokenValid ) {
				return mm;
			}*/
			
			if(!ChkUtil.isEmpty(pType)){
				
				
			}
			String searchSql = "SELECT appName,versionName,versionCode,downloadUrl,updateTime,content,flag FROM "+this.mBaseDao.tableName(Sysversion.class)+" WHERE 1=1";
			searchSql += " and flag=#{pojo.flag}";// 时间倒序排序
			searchSql += " and pType=#{pojo.pType}";// 时间倒序排序
			Map paramMap = new HashMap<>();
			if (!ChkUtil.isEmpty(flag)) {
				paramMap.put("flag",  flag);
			}else{
				paramMap.put("flag",  0);
			}
			if (!ChkUtil.isEmpty(pType)) {
				paramMap.put("pType",  pType);
			}else{
				paramMap.put("pType", 0);
			}
			
			searchSql+="  ORDER BY versionCode desc LIMIT 1";// 时间倒序排序
			
			
			sysversion = (Sysversion) this.mBaseDao.findBySqlUniqueObject(searchSql, Sysversion.class, paramMap);
			if(sysversion!=null){
				mm.put(CommonApiModelMapExt.ERRCODE, 0);
				mm.put(CommonApiModelMapExt.ERRMSG, "查询成功");
				mm.put("data",sysversion);
			}else{
				mm.put(CommonApiModelMapExt.ERRCODE, 4500);
				mm.put(CommonApiModelMapExt.ERRMSG, "无数据");
			}
			
			return mm;
		} catch (Exception e) {
			e.printStackTrace();
			mm.put(CommonApiModelMapExt.ERRCODE, 1);
			mm.put(CommonApiModelMapExt.ERRMSG, "系统异常");
			mm.put("data",sysversion);
		}
		return mm;
	}
	
	
	
	@ApiOperation(value = "护士站提醒消息", notes = "护士站提醒消息")
	@GetMapping("/getHosCallInfoConfirmList/{type}/{token}")
	@GlobalLogAnnotation(logType=2,discription="护士站提醒消息")
	public Map getHosCallInfoConfirmList(@PathVariable("type") Integer type, @PathVariable("token") String token,@RequestParam(required=true) String deviceSN , Integer pageSize,Integer curPage ) {
		CommonApiModelMapExt mm = chekTokenCahceValid(token, type);
		HosCallInfoConfirm drjm=null;
		try {
			if (!isTokenValid ||ChkUtil.isEmpty(deviceSN)) {
				return mm;
			}
			
			if(token.startsWith("demo:")){
				deviceSN=demoDeviceSN;
			}
			
			ProductDeviceInit pdi=this.getProductDeviceInit(deviceSN);
			Map paramMap = new HashMap<>();
			pageSize=pageSize==null?10:pageSize;
			curPage=curPage==null?1:curPage;
			PageBean pb = new PageBean(curPage,pageSize);
			
			PageList pl=new PageList();
			
			
			if(token.startsWith("demo:")){
				deviceSN=demoDeviceSN;
			}
			
//			String searchSql = "SELECT * FROM t_txby_hosCallInfoConfirm WHERE 1=1 and toDeviceSN =#{pojo.deviceSN} and isConfirm=0 ";and t.isConfirm!=2
			String	  searchSql = "SELECT  t.id_ msgId,t2.name sickAreaName,t.bedNO bedNO,t.updateTime callTime,t3.sickName sickName,t.callMsg discription,t.callType callType,t.isConfirm isConfirm FROM t_txby_hosCallInfoConfirm t "
			  		+ "  INNER JOIN  sys_dept t2   on t2.dept_id=t.sickAreaNO    LEFT JOIN  "
			  		+ "   t_txby_sickDetailInfo t3 on t3.bedNO=t.bedNO and t3.sickAreaNO=t.sickAreaNO and t3.deptId=t.deptId    ";
			if(pdi!=null) {
				String weekDate=DateAirth.getAirthStringDate(new Date(), 0, 0, -7);
				searchSql+=" where t.deptId="+pdi.getDeptId()+" and t.sickAreaNO="+pdi.getSickAreaNO()+" and t.toDeviceSN=#{pojo.deviceSN} and t.createTime>='"+weekDate+"' " ;
				paramMap.put("deviceSN",  deviceSN);
				searchSql += " order by t.createTime DESC";// 时间倒序排序
//				searchSql += " order by t.isConfirm ";//确认状态排序 0:未确认1：已确认2:已取消 
				 pl = this.mBaseDao.findBySqlForPageList(searchSql, Map.class, null, paramMap);
				
			}
			
			
			if(pl.getResultList().size()>0){
				mm.put(CommonApiModelMapExt.ERRCODE, 0);
				mm.put(CommonApiModelMapExt.ERRMSG, "查询成功");
				mm.put("data",pl.getResultList());
			}else{
				mm.put(CommonApiModelMapExt.ERRCODE, 4500);
				mm.put(CommonApiModelMapExt.ERRMSG, "无数据");
			}
			System.out.println(mm);
			return mm;
		} catch (Exception e) {
			e.printStackTrace();
			mm.put(CommonApiModelMapExt.ERRCODE, 1);
			mm.put(CommonApiModelMapExt.ERRMSG, "系统异常");
			mm.put("data",drjm);
		}
		System.out.println(mm);
		return mm;
	}
	
	

	@ApiOperation(value = "护士站提醒消息", notes = "护士站提醒消息")
	@GetMapping("/Test/{type}/{token}")
	@GlobalLogAnnotation(logType=2,discription="护士站提醒消息")
	public Map Test(@PathVariable("type") Integer type, @PathVariable("token") String token,String test) {
		
		return null;
	}
	
	
	@ApiOperation(value = "获取消息反馈", notes = "获取消息反馈")
	@GetMapping("/getsuggestion/{type}/{token}")
	@GlobalLogAnnotation(logType=2,discription="获取消息反馈")
	public Map getsuggestion(@PathVariable("type") Integer type, @PathVariable("token") String token ,Integer paperId) {
		CommonApiModelMapExt mm = chekTokenCahceValid(token, type);
		
		try {
			/*if (!isTokenValid ||ChkUtil.isEmpty(paperId)) {
				return mm;
			}*/
			
			Map paramMap = new HashMap<>();
			Set name = new HashSet<>();
			
			String searchSql = "SELECT t1.id_ as paperId, t1.name, t2.id_ as topicId, type, topic FROM t_txby_bd_sysPaper t1, t_txby_bd_sysCusTopic t2, t_txby_bd_sysOption t3 WHERE t1.id_ = t2.paperId AND t2.id_ = t3.topicId ";
			if(!ChkUtil.isEmpty(paperId)){
				searchSql+=" and t1.id_="+paperId+"";
			}
			
			searchSql += " GROUP BY t2.id_ order by t2.id_ ";// 时间倒序排序
			Map map_ = new HashMap<>();
			List list_total = new ArrayList();
			List list = (List) this.mBaseDao.findBySql(searchSql, Map.class, paramMap);
			for(int i = 0 ; i < list.size() ; i++) {
				  map_ = (Map) list.get(i);
				  String sql_type = (list.get(i).toString().split(",")[0].split("=")[1].replaceAll("}", "")).toString();
				   List optionList =  (List) getOption(new Integer(sql_type));
				   map_.put("option", optionList);
				   list_total.add(map_);
			}
			
			if(list!=null){
				mm.put(CommonApiModelMapExt.ERRCODE, 0);
				mm.put(CommonApiModelMapExt.ERRMSG, "查询成功");
				mm.put("data",list_total);
			}else{
				mm.put(CommonApiModelMapExt.ERRCODE, 4500);
				mm.put(CommonApiModelMapExt.ERRMSG, "无数据");
			}
			
			
			return mm;
		} catch (Exception e) {
			e.printStackTrace();
			mm.put(CommonApiModelMapExt.ERRCODE, 1);
			mm.put(CommonApiModelMapExt.ERRMSG, "系统异常");
			mm.put("data",null);
		}
		return mm;
	}
	
	
	@ApiOperation(value = "保存反馈答案", notes = "保存反馈答案")
	@PostMapping("/savesuggestion/{type}/{token}")
	@GlobalLogAnnotation(logType=2,discription="保存反馈答案")
	public Map savesuggestion(@PathVariable("type") Integer type, @PathVariable("token") String token, @RequestBody String content ) {
		CommonApiModelMapExt mm = chekTokenCahceValid(token, type);
		
		try {
		/*	if (!isTokenValid) {
				return mm;
			}
			*/
			  //String content = "[{\"checked_\":[\"2\"],\"id_\":1,\"paperId\":1,\"patient_id\":14,\"type\":1},{\"checked_\":[\"5\",\"6\"],\"id_\":2,\"paperId\":1,\"patient_id\":14,\"type\":2},{\"checked_\":[\"9\",\"上档次颠三倒四\"],\"id_\":3,\"paperId\":1,\"patient_id\":14,\"type\":3}]";
			  //String content ="[{\"checked_\":[\"59\"],\"id_\":0,\"paperId\":1,\"patient_id\":14,\"type\":1},{\"checked_\":[\"64\"],\"id_\":0,\"paperId\":1,\"patient_id\":14,\"type\":1},{\"checked_\":[\"3\"],\"id_\":0,\"paperId\":1,\"patient_id\":14,\"type\":1},{\"checked_\":[\"69\",\"70\"],\"id_\":0,\"paperId\":1,\"patient_id\":14,\"type\":2},{\"checked_\":[\"5\",\"6\"],\"id_\":0,\"paperId\":1,\"patient_id\":14,\"type\":2},{\"checked_\":[\"78\",\"qwe\"],\"id_\":0,\"paperId\":1,\"patient_id\":14,\"type\":3}]";
			  JSONArray json = JSONArray.fromObject(content);//content是json字符串
			  List users= (List)JSONArray.toCollection(json, Map.class);//转成list
			  SysAnswer sysAnswer = new SysAnswer();
			  for (int i = 0; i < users.size(); i++) {//循环最外层的list
				  //System.out.println(users.get(i));
				  Map map = (Map) users.get(i);
				  sysAnswer.setTopicId(new Integer(map.get("topicId").toString()));//题干
				  sysAnswer.setPaperId(new Integer(map.get("paperId").toString()));//试题id
				  sysAnswer.setUserId(new Integer(map.get("patient_id").toString()));//患者id
				  String type1 = map.get("type").toString();//类型：1单选2多选3简答
				  sysAnswer.setType(new Integer(type1));
				  String optionId = map.get("checked_").toString();//选择的值
				  if (new Integer(type1) == 3) {
					  String list = optionId.substring(1,optionId.length()-1);
					  String[] l = list.toString().split(",");
					  sysAnswer.setOptionId(new Integer(l[0]));
					  sysAnswer.setContent(l[1].toString().trim());
				  /*sysAnswer.setContent(map.get("checked_").toString().substring(1,map.get("checked_").toString().length()-1));
				  sysAnswer.setOptionId(new Integer(optionId.substring(1,optionId.length()-1)));*/
				  this.mBaseDao.saveObject(sysAnswer);
				 // System.out.println(sysAnswer);
				}else if(new Integer(type1) == 1){
					sysAnswer.setOptionId(new Integer(optionId.substring(1,optionId.length()-1)));
					sysAnswer.setContent(null);
					this.mBaseDao.saveObject(sysAnswer);
					//System.out.println(sysAnswer);
				}else if(new Integer(type1) == 2){
					String list = optionId.substring(1,optionId.length()-1);
					String[] l = list.toString().split(",");
					for (int j = 0; j < l.length; j++) {
						sysAnswer.setOptionId(new Integer(l[j].trim()));
						sysAnswer.setContent(null);
						this.mBaseDao.saveObject(sysAnswer);
						//System.out.println(sysAnswer);
					}
				}
			}
			
				mm.put(CommonApiModelMapExt.ERRCODE, 0);
				mm.put(CommonApiModelMapExt.ERRMSG, "保存成功");
			
			return mm;
		} catch (Exception e) {
			e.printStackTrace();
			mm.put(CommonApiModelMapExt.ERRCODE, 1);
			mm.put(CommonApiModelMapExt.ERRMSG, "系统异常");
		}
		return mm;
	}
	

	/**
	 * 
	 * @param id
	 * @return 题目的选项
	 */
	private Object getOption(int id) {
		String sql="select value,id_ FROM t_txby_bd_sysOption WHERE 1=1 ";
		if(!ChkUtil.isEmpty(id)){
			sql+=" and topicId="+id+"";
		}
		Object optionmap=(Object) this.mBaseDao.findBySql(sql, Map.class, null);
		return optionmap;
	}
	
	@ApiOperation(value = "统计答题人数", notes = "统计答题人数")
	@GetMapping("/getAddUpSuggestion/{type}/{token}")
	@GlobalLogAnnotation(logType=2,discription="统计答题人数")
	public Map getAddUpSuggestion(@PathVariable("type") Integer type, @PathVariable("token") String token ,Integer optionId) {
		CommonApiModelMapExt mm = chekTokenCahceValid(token, type);
		
		try {
			if (!isTokenValid ||ChkUtil.isEmpty(optionId)) {
				return mm;
			}
			if (!ChkUtil.isEmpty(optionId)) {
				Map paramMap = new HashMap<>();
				List list = new ArrayList();
				String sql = "SELECT type FROM t_txby_bd_sysOption t1, t_txby_bd_sysCusTopic t2 WHERE t1.topicId = t2.id_ AND t1.id_ = #{pojo.optionId}";
				paramMap.put("optionId",  optionId);
				Map map =(Map) this.mBaseDao.findBySqlUniqueObject(sql, Map.class, paramMap);
				String topic_type = map.get("type").toString();
				if (topic_type.equals("1")||topic_type.equals("2")) {
					 paramMap = new HashMap<>();
					 sql = "select DISTINCT t2.value, (((SELECT count(*) FROM `t_txby_bd_sysAnswer` where optionId = #{pojo.optionId})*100)/ (SELECT count(*) FROM `t_txby_bd_sysAnswer`"
					 		+ " where topicId = "+topic_type+")) as percent from t_txby_bd_sysAnswer t1,t_txby_bd_sysOption t2 where t1.optionId = t2.id_ and t1.optionId = #{pojo.optionId}";
					paramMap.put("optionId",  optionId);
					 map =(Map) this.mBaseDao.findBySqlUniqueObject(sql, Map.class, paramMap);
				}else if (topic_type.equals("3")) {
					 paramMap = new HashMap<>();
					 sql = "select DISTINCT t1.content, (((SELECT count(*) FROM `t_txby_bd_sysAnswer` where optionId = #{pojo.optionId})*100)/ (SELECT count(*) FROM `t_txby_bd_sysAnswer`"
					 		+ " where topicId = "+topic_type+")) as percent from t_txby_bd_sysAnswer t1,t_txby_bd_sysOption t2 where t1.optionId = t2.id_ and t1.optionId = #{pojo.optionId}";
					paramMap.put("optionId",  optionId);
					 list =(List) this.mBaseDao.findBySql(sql, Map.class, paramMap);
					 
				}
				 if(list.size()>0){
					mm.put("data",list);
					mm.put(CommonApiModelMapExt.ERRCODE, 0);
					mm.put(CommonApiModelMapExt.ERRMSG, "该简答题占比如下");
				}else if (map!=null) {
					mm.put("data",map);
					mm.put(CommonApiModelMapExt.ERRCODE, 0);
					mm.put(CommonApiModelMapExt.ERRMSG, "该选项占比如下");
				}
				else{
					mm.put(CommonApiModelMapExt.ERRCODE, 1);
					mm.put(CommonApiModelMapExt.ERRMSG, "该选项还没有选择");
				}
			}
			
			
			return mm;
		} catch (Exception e) {
			e.printStackTrace();
			mm.put(CommonApiModelMapExt.ERRCODE, 1);
			mm.put(CommonApiModelMapExt.ERRMSG, "系统异常,没有该选项");
			mm.put("data",null);
		}
		return mm;
	}
}